//
//  PersonalCenterViewController.m
//  HomeDelivery
//
//  Created by apple on 16/7/25.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "PersonalCenterViewController.h"
#import "ForgetPassWordViewController.h"
#import "AlterNickNameViewController.h"
#import "CustomSheetView.h"
@interface PersonalCenterViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate>
@property(nonatomic,strong)UITableView *mainTableView;
@property(nonatomic,strong)NSDictionary *dataDic;
@property(nonatomic,strong)UIImage *headImage;

@end

@implementation PersonalCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"个人中心";
    self.view.backgroundColor=LIGHTGRAY;
    self.automaticallyAdjustsScrollViewInsets=NO;
    [self.view addSubview:self.mainTableView];
    if ([self.mainTableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.mainTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.mainTableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.mainTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    [self setUpBottomView];
    [self getData];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshTabBar) name:@"refreshTabBar" object:nil];
}
-(void)refreshTabBar
{
    [self getData];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark--表分割线条通栏
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
}
#pragma mak--获取首页数据
-(void)getData
{
    //http://192.168.1.107:35568/User/PersonalCenter/{AdminAccount}/{VerNumber}/{ClientType}/{Timestamp}/{Sign}
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"AdminAccount":ADMINACCOUNT,
                        @"VerNumber":VERNUM,
                        @"ClientType":CLIENTTYPE,
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"User/PersonalCenter/%@/%@/%@/%@/%@",ADMINACCOUNT,VERNUM,CLIENTTYPE,timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andFinishedWith:^(id response, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (error)
        {
            [MBProgressHUD showError:@"请求失败"];
        }else
        {
            if ([response[@"IsSuccess"]integerValue]==1)
            {
                _dataDic=response[@"ReturnObject"];
                [_mainTableView reloadData];
            }else
            {
                [MBProgressHUD showError:response[@"ReturnString"]];

            }
        }
    }];
}
#pragma mark--按钮
-(void)setUpBottomView
{
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.mainTableView.frame)+15, WIDTH, 48)];
    btn.backgroundColor=[UIColor whiteColor];
    btn.layer.cornerRadius=5;
    btn.clipsToBounds=YES;
    btn.titleLabel.font=[UIFont systemFontOfSize:17];
    [btn setTitle:@"退出登录" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickOnBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
//退出登录
-(void)clickOnBtn
{
    NSUserDefaults *data=[NSUserDefaults standardUserDefaults];
    [data removeObjectForKey:@"AdminAccount"];
    [data synchronize];
    
    LoginViewController *login=[[LoginViewController alloc]init];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:login];
    UIWindow *window=[UIApplication sharedApplication].keyWindow;
    window.rootViewController=nav;

}
#pragma mark--表
-(UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, 295) style:UITableViewStylePlain];
        _mainTableView.delegate=self;
        _mainTableView.dataSource=self;
        _mainTableView.scrollEnabled=NO;
        _mainTableView.tableFooterView=[UIView new];
    }
    return _mainTableView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 80;
    }else
    {
        return 50;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"reuse"];
        cell.textLabel.textColor=[UIColor darkGrayColor];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.detailTextLabel.textColor=[UIColor lightGrayColor];
        cell.imageView.layer.cornerRadius=cell.imageView.frame.size.height/2.0;
        cell.imageView.clipsToBounds=YES;
        cell.detailTextLabel.font=[UIFont systemFontOfSize:13];
        UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(15, 10, 60, 60)];
        imageView.layer.cornerRadius=30;
        imageView.clipsToBounds=YES;
        imageView.tag=100;
        [cell.contentView addSubview:imageView];
        
    }
    cell.detailTextLabel.text=nil;
    cell.accessoryView=nil;
    NSArray *textArr=@[@"用户昵称",@"登录密码",@"已绑定手机号",@"所属店铺"];
    NSArray *detailArr=@[@"设置头像",@"设置昵称",@"修改密码",@"",@""];
    if (indexPath.row==0)
    {
        cell.detailTextLabel.text=detailArr[indexPath.row];
    }else
    {
        cell.textLabel.text=textArr[indexPath.row-1];
    }
   
    if (_dataDic) {
    if (indexPath.row==0)
    {
        UIImageView *image=[cell.contentView viewWithTag:100];
        if (_headImage) {
            
            image.image=_headImage;
        }else
        {
            
            [image sd_setImageWithURL:[NSURL URLWithString:_dataDic[@"HeadImg"]] placeholderImage:nil options:SDWebImageRetryFailed];
        }

        
    }else
    {
            if (indexPath.row==0)
            {
                if ([_dataDic[@"HeadImg"]isEqualToString:@""])
                {
                    cell.detailTextLabel.text=@"设置头像";
                }else
                {
                  cell.detailTextLabel.text=@"修改头像";
                }
                
            }
            if (indexPath.row==1)
            {
                if ([_dataDic[@"NickName"]isEqualToString:@""])
                {
                    cell.detailTextLabel.text=@"设置昵称";
                }else
                {
                  cell.detailTextLabel.text=_dataDic[@"NickName"];
                }
            }
            if (indexPath.row==2)
            {
                cell.detailTextLabel.text=@"修改密码";
            }
            if (indexPath.row==3)
            {
                if (![_dataDic[@"Mobile"]isEqualToString:@""])
                {
                    NSString *str=_dataDic[@"Mobile"];
                   cell.detailTextLabel.text=[str stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
                }
            }
            if (indexPath.row==4)
            {
              cell.detailTextLabel.text=_dataDic[@"MerchantName"];
            }

        }
    }
    UIImageView *imageview=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_icon_1"]];
    imageview.frame=CGRectMake(WIDTH-10, 15, 10, 20);
    if (indexPath.row==0 || indexPath.row==1 || indexPath.row==2)
    {
        cell.accessoryView=imageview;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
    {
        [CustomSheetView sharedSheetWithPhotoBlock:^{
            [self addCarema];
        } andPictureBlock:^{
            [self addPhotos];
        } andCancleBlock:^{
            // do nothing
        }];

    }else if (indexPath.row==1)
    {
        AlterNickNameViewController *alterName=[[AlterNickNameViewController alloc]init];
        alterName.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:alterName animated:YES];
    }else if (indexPath.row==2)
    {
        ForgetPassWordViewController *forget=[[ForgetPassWordViewController alloc]init];
        forget.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:forget animated:YES];
 
    }
}
#pragma mark -carema
-(void)addCarema{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        //如果没有提示用户
        [MBProgressHUD showError:@"请去设置里面允许应用访问相机"];
    }
}
-(void)addPhotos
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.editing = YES;
        imagePicker.allowsEditing = YES;
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePicker animated:YES completion:^{
        }];
    }else
    {
        [MBProgressHUD showError:@"请去设置里面允许应用访问相册"];
    }
    
}
#pragma mark 上传头像
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *editedImage, *originalImage;
        
        //获得image
        editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
        originalImage =[info objectForKey:UIImagePickerControllerOriginalImage];
        
        //处理图片 存储，上传至服务器
        [MBProgressHUD showMessage:@"图片上传中……" toView:self.view];
        [self uploadToOriginWithImage:originalImage WithComlete:^(BOOL isSuccess) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            _headImage = nil;
            if (isSuccess) {
                _headImage = editedImage;
            }
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [_mainTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];        }];
        
        // 保存原图片到相册中
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            UIImageWriteToSavedPhotosAlbum(originalImage, self, nil, NULL);
        }
        
    }];
}
-(void)uploadToOriginWithImage:(UIImage *)originalImage WithComlete:(void(^)(BOOL isSuccess))block
{
//    //http://192.168.1.107:35568/User/FileUploadBase
//    NSString *timestamp=[GeneralTool gettimestamp];
//    NSData *imgData = UIImageJPEGRepresentation(originalImage, 0.01);
//    NSDictionary *dic=@{@"AdminAccount":ADMINACCOUNT,
//                        @"ImageType":@"jpg",
//                        @"ClientType":CLIENTTYPE,
//                        @"Timestamp":timestamp};
//    NSString *sign=[GeneralTool GetSin:dic];
//    NSDictionary *requestDic=@{@"AdminAccount":ADMINACCOUNT,
//                               @"ImageType":@"jpg",
//                               @"ClientType":CLIENTTYPE,
//                               @"Timestamp":timestamp,
//                               @"Sign":sign};
//   // [RequestTool upload:@"ImageContext" filename:@"1.jpg" mimeType:@"image/jpeg" data:imgData parmas:requestDic];
//    [RequestTool uploadImageURLString:@"User/HandImgUpload" WithDict:requestDic andNSData:imgData andBlock:^(id data, NSError *error) {
//        if (data&&[[data objectForKey:@"IsSuccess"]integerValue]==1)
//        {
//            block(YES);
//        }else
//        {
//            block(NO);
//        }
//
//    }];
    
    NSString *timestamp=[GeneralTool gettimestamp];
    
    NSData *imgData = UIImageJPEGRepresentation(originalImage, 0.6);
    NSString * dataString = [GTMBase64 stringByEncodingData:imgData];
    
    NSDictionary * dataDic = @{@"AdminAccount":ADMINACCOUNT,@"ImageType":@"jpg",@"ClientType":CLIENTTYPE,@"Timestamp":timestamp};
    NSString * sign = [GeneralTool GetSin:dataDic];
    NSDictionary * requestDic = [NSDictionary dictionaryWithObjects:@[ADMINACCOUNT,@"jpg",CLIENTTYPE,timestamp,dataString,sign] forKeys:@[@"AdminAccount",@"ImageType",@"ClientType",@"Timestamp",@"ImageContent",@"Sign"]];
        [RequestTool requestDataWithType:@"post" andUrlString:@"User/FileUploadBase" andParameters:@{@"m_FileUploadBasePara":requestDic} andFinishedWith:^(id response, NSError *error) {
        if (response&&[[response objectForKey:@"IsSuccess"]integerValue]==1)
        {
            block(YES);
        }else
        {
            block(NO);
        }
 
    }];
   
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor=ORANGE;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:18]};
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
